package com.example.happiness.controller.user;

import com.example.happiness.constant.JwtClaimsConstant;
import com.example.happiness.pojo.User;
import com.example.happiness.pojo.uservo.UserLoginVO;
import com.example.happiness.properties.JwtProperties;
import com.example.happiness.result.Result;
import com.example.happiness.service.user.UserService;
import com.example.happiness.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    JwtProperties jwtProperties;


    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public Result<UserLoginVO> userlogin(@RequestBody User user){
        System.out.println(user.getUserid()+","+user.getPassword());
        User uservo = userService.userLogin(user);
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if (uservo == null) {
            return Result.error("手机号未注册");
        }else if(!uservo.getPassword().equals(password)){
            return Result.error("密码错误");
        }
        Map<String,Object> claims = new HashMap();
        claims.put(JwtClaimsConstant.USER_ID,user.getUserid());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .user(uservo)
                .token(token)
                .build();
        return Result.success(userLoginVO);
    }

    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public Result<User> register(@RequestBody User user){
        return userService.register(user);
    }

    @PostMapping("/updataUserInfo")
    @ApiOperation(value = "修改用户信息")
    public Result updataUserInfo(@RequestBody User user){
        userService.updataUserInfo(user);
        return Result.success();
    }
}
